package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.EmpExprMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.*;
import com.itheima.service.DeptService;
import com.itheima.service.EmpService;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.javassist.expr.Expr;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmpServiceImpl extends ServiceImpl<EmpMapper, Emp> implements EmpService {
    @Autowired
    private DeptService deptService;
    @Autowired
    private EmpExprMapper empExprMapper;

    /**
     * 分页查询
     *
     * @return
     */
    @Override
    public PageResult<Emp> findpage(EmpQueryParam param) {
        // 2.创建分页对象
        IPage<Emp> pagination = new Page<>(param.getPage(), param.getPageSize());
        //进行条件查询
        //1调用service中分页方法
        LambdaQueryWrapper<Emp> queryWrapper = Wrappers.<Emp>lambdaQuery()
                .like(param.getName() != null, Emp::getName, param.getName())
                .eq(param.getGender() != null, Emp::getGender, param.getGender())
                .between(param.getBegin() != null && param.getEnd() != null, Emp::getEntryDate, param.getBegin(), param.getEnd());
        queryWrapper.orderByDesc(Emp::getUpdateTime);

        IPage<Emp> pageResult = this.page(pagination, queryWrapper);
        //3.获取分页结果，得到当前页的数据
        List<Emp> empList = pageResult.getRecords();
        //5.获取总记录数，就是总条数
        Long total = pageResult.getTotal();

        //解决部门名称不显示的问题，注意，此时empList中没有部门名称
        //1.关联封装emp中的deptName
        List<Integer> deptId = empList.stream().map(emp -> emp.getDeptId()).toList();
        //将得到的部门ID集合去重
        deptId = deptId.stream().distinct().toList();
          if(!CollectionUtils.isEmpty(deptId)){
              List<Dept> deptList = deptService.listByIds(deptId);//通过deptId集合查询部门列表
              // 双重for循环，实现为每一个emp实体对象中的deptName属性进行赋值
              empList.forEach(emp -> deptList.stream().filter(dept -> dept.getId().equals(emp.getDeptId()))
                      .findFirst()//返回值optional，这是一个容器对象
                      .ifPresent(dept -> emp.setDeptName(dept.getName()))
              );
          }
        return new PageResult<>(total, empList);
    }

    /**
     * 增加员工
     *
     * @param emp
     * @return
     */
    @Override
    @Transactional
    public void add(Emp emp) {
        emp.setPassword("123456");
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        this.save(emp);//添加员工表
        //添加员工经历表
        List<EmpExpr> exprList = emp.getExprList();
        if (!CollectionUtils.isEmpty(exprList)) {
            for (EmpExpr empExpr : exprList) {
                empExpr.setEmpId(emp.getId());
            }
            empExprMapper.insert(exprList);
        }
    }

    /**
     * 查询回显
     *
     * @param id
     * @return
     */
    @Override
    public Emp getByList(Integer id) {
        //查询员工表
        Emp emp = this.getById(id);
        //查询员工经历表
        List<EmpExpr> list = empExprMapper.selectList(Wrappers.<EmpExpr>lambdaQuery().eq(EmpExpr::getEmpId, emp.getId()));
        //封装
        emp.setExprList(list);
        return emp;
    }

    /**
     * 修改员工
     *
     * @param emp
     */
    @Override
    public void updateEmp(Emp emp) {
        //修改员工
        emp.setUpdateTime(LocalDateTime.now());
        this.updateById(emp);
        //删除员工工作经历
        List<EmpExpr> exprList = empExprMapper.selectList(Wrappers.<EmpExpr>lambdaQuery().eq(EmpExpr::getEmpId, emp.getId()));
        empExprMapper.deleteByIds(exprList);

        //再新增员工工作经历
        List<EmpExpr> exprList1 = emp.getExprList();
        if(!CollectionUtils.isEmpty(exprList1)){
            for (EmpExpr empExpr : exprList) {
                empExpr.setEmpId(emp.getId());
            }
            empExprMapper.insert(exprList1);
        }

    }

    /**
     * 删除员工
     *
     * @param ids
     */
    @Override
    @Transactional
    public void deleted(List<Integer> ids) {
        this.removeByIds(ids);//先根据ID删除员工表
        empExprMapper.delete(Wrappers.<EmpExpr>lambdaQuery().in(EmpExpr::getEmpId,ids));
    }
}
